import uuid

from django.db import models
from django.utils import timezone

from apps.QuestionManagement.models import Questions
from apps.UserManagement.models import User


class Paper(models.Model):
    """试卷记录表"""
    objects = models.Manager()

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)

    exam_name = models.CharField(max_length=200, help_text="考试名称")

    exam_description = models.TextField(max_length=500, help_text="考试说明", blank=True, null=True)  # 考试说明，可为空

    exam_duration = models.IntegerField(help_text="考试时长（分钟）", default=60)  # 考试时长，单位为分钟 默认考试时长为60分钟

    total_score = models.IntegerField(default=0, help_text='总分')

    # 是否发布
    status = models.BooleanField(default=False, help_text='是否发布')

    # 创建人（外键）
    created_user = models.ForeignKey(User, related_name='created_paper', on_delete=models.SET_NULL, null=True,
                                     blank=True)
    # 创建时间
    created_at = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新人（外键）
    updated_user = models.ForeignKey(User, related_name='updated_paper', on_delete=models.SET_NULL, null=True,
                                     blank=True)
    # 更新时间
    updated_at = models.DateTimeField(auto_now=True, null=True, help_text='更新时间')

    class Meta:
        db_table = 'paper'
        verbose_name = "试卷记录"
        verbose_name_plural = "试卷记录"

    is_random = models.BooleanField(default=False, help_text='是否随机排序')

    def __str__(self):
        return (f"考试名称: {self.exam_name}, 考试说明: {self.exam_description}"
                f", 考试时长（分钟）:{self.exam_duration}")


class PaperQuestion(models.Model):
    """试卷试题关联表"""
    objects = models.Manager()
    question = models.ForeignKey(Questions, on_delete=models.CASCADE)
    paper = models.ForeignKey(Paper, on_delete=models.CASCADE)
    score = models.IntegerField(default=0, help_text="试题分值")

    class Meta:
        db_table = 'paper_question'
        unique_together = ('question', 'paper')
